package com.fingard.dsp.bank.directbank.jhbank01.utils;

import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class PublickeyEncript {


	/**
	 * 公钥加密
	 * @param json
	 * @param certificatePath
	 * @return
	 * @throws Exception
     */
	public static Map<String, String> encryptData(String json,String certificatePath) throws Exception {
		// 获取公钥
		PublicKey pubKeyFromCrt = RSA.getPubKeyFromCRT(certificatePath);
		// 随机生成16数字
		String key = getRandom(16);
		// 使用RSA算法将自己随机生成的AESkey加密
		String encryptKey = RSA.encrypt(key, pubKeyFromCrt);
		// 使用AES算法用随机生成的AESkey，对json串进行加密
		String encryData = AES.encryptToBase64(json, key);
		Map<String, String> map = new HashMap<String, String>();
		map.put("encryptdata", encryData);
		map.put("encryptkey", encryptKey);

		return map;
	}
	
	public static Random random = new Random();

	public static String getRandom(int length) {
		StringBuilder ret = new StringBuilder();
		for (int i = 0; i < length; i++) {
			boolean isChar = (random.nextInt(2) % 2 == 0);// 输出字母还是数字
			if (isChar) { // 字符串
				int choice = (random.nextInt(2) % 2 == 0) ? 65 : 97; // 取得大写字母还是小写字母
				ret.append((char) (choice + random.nextInt(26)));
			} else { // 数字
				ret.append(Integer.toString(random.nextInt(10)));
			}
		}
		return ret.toString();
	}
	
	public static void main(String args[]){
		String path = "D:/certificate/jhbank.cer";
        try {
        	String reqStr = "公钥加密";
            //加密
            System.err.println("公钥加密");
			Map<String,String>  map = PublickeyEncript.encryptData(reqStr,path);
			System.err.println("公钥验证签名");
	        String reqStr2="EJn4jUds9FwU1r7mDkJkJUrIw90ox1nQzUNLZH";
	        //对reqStr2数字签名后得到str
	        String str="f4R+u/2IN72O7dmHj5Y7WCEWr9nDklBh7ToFMGJVNs+339274o0iRxFAO8aOlVfXmezpFpOCtUmjUKnXUzKGPILQcKwv1WyxL8TdPm7GFhmY8Wikcl2ciwlk1SZwbyxuQg5uLMod1SC1sATTR29/tYfaNEEBTIQpaMlxsGKEzBF2UPnwg6zKcfNZMeFVGDuoc6pIBWSkNTK34cE111DepOu8EKxOfJyx9mvJHTt2UX8nhroaWtYTxGkTz8A0LwrCtdfqgnQnJ/H/O1GAffFlZMUCb2vhJgfC4je9y6d7W1vm+pBMxPZaVXwmde/XXW7pOl+DfqjAUAqxhIjtd7Qhtw==";
	        boolean b=PublickeyEncript.checkSign(reqStr2, str,path);
	        System.out.println("签名验证结果："+b);
        } catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	/**
	 * 检查数字证书签名
	 * @param str
	 * @param sign
	 * @return
	 * @throws Exception
	 */
	public static boolean checkSign(String str,String sign,String certificatePath) throws Exception{
		PublicKey pubKeyFromCrt = RSA.getPubKeyFromCRT(certificatePath);
		boolean  b=RSA.checkSign(str, sign, pubKeyFromCrt);
		return b;
		
	}
	
}
